package gui;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import java.util.Locale;


import javax.swing.ImageIcon;
import javax.swing.JButton;

import javax.swing.JInternalFrame;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;

import javax.swing.KeyStroke;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.JTextComponent;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import Lexicon.Lexicon;
import Lexicon.WordType;
import Main.ArToEn;
import Main.MyNormalizer;
import Main.Tokenizer;

import parser.ArabicParser;

/* Used by InternalFrameDemo.java. */

public class TranslationFrame extends JInternalFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5317379143439725029L;
	static int openFrameCount = 0;
	static final int xOffset = 30 ;
	static final int yOffset = 20 ;
	static int xLocation;
	static int yLocation;
	JSplitPane splitPane;
	JSplitPane topSplit , split ;
	public static JTextArea input;
	public JTextArea output;
	//private JFormattedTextField arWord;
	//private JButton searchButton;
	//private JFormattedTextField engWord;
	private JTabbedPane tranTab ;
	ScrollPane spInput;
	ScrollPane spOutput;
//	static final private String OPEN = "open";
//	static final private String SAVE = "save";
	static final private String NEW = "new";
	static final private String IMPORT_DIC = "Import_dic";
	static final private String DIC_CUR = "current_dic" ;
	static final private String DIC_MOD = "modify_dic" ;
	static final private String DIC_NEW = "new_dic" ;
	static final private String IMPORT_TXT = "Import_txt";
	static final private String EXPORT_DIC = "Export_dic";
	static final private String EXPORT_TXT = "Export_txt";
	static final private String PARSE ="parse";
	static final private String PRINT = "print";
	static final private String QTranslation = "qtranslate";
	static final private String ATranslation = "atranslate";
	static final private String QUITE = "quite";
	static final String TRANS = "translate";
	String imgLocation ;
	ArMT gui ;
	ArToEn artoen ;
	SearchPanel sp ;
	AdditionPanel ap ;
	JScrollPane dicPane ,treePane ;
	JTextField tf ;
	JPanel analyzeP ;
//	JFileChooser dicChooser = new JFileChooser();
//	JFileChooser txtChooser =new JFileChooser();
//	JFileChooser saveDic = new JFileChooser();
//	JFileChooser saveTxt = new JFileChooser();
	//private JPanel statusBar;
	String [] xmlFilter = {"xml"};
	String [] txtFilter = {"txt","doc"};
	FileNameExtensionFilter xmlExten = new FileNameExtensionFilter ( "XML Files" , xmlFilter) ;
	FileNameExtensionFilter txtExten = new FileNameExtensionFilter ( "Text Files" ,txtFilter) ;
	TranslationFrame transFrame ;
	private File currentDirectory;
    private File sourceFile;
    private File targetFile;
    JPanel encPanel ;
    private String[] encOptions = {"Cp420", "Cp1256", "ISO8859_6", "MacArabic", "UTF8", "UTF-16"};
    String encoding = "Cp1256"; 
    JComboBox encodingOptions ;
    Lexicon lex ;
    DicTable dicTable ;
	@SuppressWarnings("deprecation")
	public TranslationFrame() throws SAXException, IOException, ParserConfigurationException {
		super(ArMT.labels.getString("newDoc")+"#" + (++openFrameCount), 
				true, //resizable
				true, //closable
				true, //maximizable
				true);//iconifiable
		setTitle(ArMT.labels.getString("newDoc")+"#" + (++openFrameCount));
		setSize(650,570);
		//xLocation = xOffset+openFrameCount ; //xOffset*openFrameCount ;
		//yLocation =yOffset+openFrameCount ; //yOffset*openFrameCount ;
		//setLocation(xLocation,yLocation );
		setLayout(new BorderLayout());
		setOpaque(true);
		JMenuBar mb =  createMenuBar() ;
		setMenuBar(mb); 
		
		currentDirectory = new File("resources");
		
		lex = new Lexicon();

		{input=new JTextArea();
		input.setText(ArMT.labels.getString("inputString"));
		input.setLocale(new Locale("ar","EG"));
		//input.addCaretListener();
		input.repaint();
		input.setEditable(true);
		input.setFont(new Font("Lucida Sans", Font.BOLD, 12));
		
		spInput = new ScrollPane();
		spInput.add(input);
		spInput.setBounds(286,5,195, 273);
		spInput.repaint();

		// ���� �������
		output=new JTextArea();
		output.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
		output.repaint();
		spOutput = new ScrollPane();

		spOutput.add(output);
		spOutput.setBounds(5, 5, 195, 273);
		spOutput.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
		spOutput.repaint();
		}

		JToolBar toolBar = new JToolBar();
		toolBar.setLayout(new FlowLayout(FlowLayout.LEFT,10,3));
		
		
		dicTable = new DicTable() ;
		dicTable.setDicState(DicTable.MODIFY);
		//dicPane = new JScrollPane(dicTable);
		
		ap = new AdditionPanel() ;
		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, spInput, spOutput);
		split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,ap,new JScrollPane(dicTable));
		split.repaint();

		if(ArMT.co == ComponentOrientation.RIGHT_TO_LEFT)
		{
			toolBar.setLayout(new FlowLayout(FlowLayout.RIGHT,10,3));
			splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, spOutput, spInput);
//			split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,new JScrollPane(new DicTable()),new AdditionPanel());
		}        
		addButtons(toolBar);

		add(toolBar, BorderLayout.PAGE_START);  

		split.setOneTouchExpandable(true);
		split.setDividerLocation(300);

		splitPane.setOneTouchExpandable(true);
		splitPane.setDividerLocation(300);

		treePane = new JScrollPane ();
		analyzeP = new JPanel();

		tf = new JTextField("����");
		analyzeP.add(tf ,BorderLayout.NORTH);
		JButton b = new JButton("Analyze");
//		b.addActionListener(new ActionListener()
//		{
//			public void actionPerformed(ActionEvent ae)
//			{
//				try {
//					treePane.add(new ParseTree(tf.getText().split("\\s")));	
////					DefaultMutableTreeNode arSentenceNode = new DefaultMutableTreeNode("Arabic-Sentence");
////					DefaultTreeModel arSen = new DefaultTreeModel(arSentenceNode) ;
////				    JTree arSenTree = new JTree(arSen);
////				    analyzeP.add(arSenTree);
////					add(arSenTree);
//			} catch (UnsupportedLookAndFeelException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//			}
//			}
//		});
		analyzeP.add(b , BorderLayout.EAST);
		analyzeP.add(treePane ,BorderLayout.CENTER) ;
		
		
		tranTab = new JTabbedPane();
		tranTab.addTab(ArMT.labels.getString("translationTab"), splitPane);
		tranTab.addTab(ArMT.labels.getString("AddNewWordTab"), split);
		//tranTab.addTab("Analyze", analyzeP);
		
		


		sp = new SearchPanel();
		topSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT,tranTab,sp);
		topSplit.setOneTouchExpandable(true);
		topSplit.setDividerLocation(370);

		add(topSplit ,BorderLayout.CENTER);


		/****************Apply Orientation*********************/
		Component c [] = {split , tranTab ,topSplit  ,this ,mb} ;
		//JTextComponent[] engC = {output , sp.getEngWord() , ap.getEnWord()};
		//JTextComponent[] arC = {input , sp.getArWord() , ap.getArWord() } ;
		for(int y = 0 ; y < c.length ; y++)
		{
			ArMT.applyComponentOrientation(c[y], ArMT.co);		
		}
//		for(int l=0 ;l<engC.length;l++)
//			ArMT.applyComponentOrientation(engC[l], ComponentOrientation.LEFT_TO_RIGHT) ;
//		for(int l=0 ;l<arC.length;l++)
//			ArMT.applyComponentOrientation(arC[l], ComponentOrientation.RIGHT_TO_LEFT) ;
	}
	public JMenuBar createMenuBar() {
		JMenuBar menuBar = new JMenuBar();

		//Set up the File menu.
		{
			JMenu fileMenu = new JMenu(ArMT.labels.getString("fileMenu"));
			fileMenu.setMnemonic(KeyEvent.VK_F);
			fileMenu.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			menuBar.add(fileMenu);

			//Set up the new menu item.
			JMenuItem newMenuItem = new JMenuItem(ArMT.labels.getString("fileNewMenue"));
			newMenuItem.setMnemonic(KeyEvent.VK_N);
			newMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_N, ActionEvent.ALT_MASK));
			newMenuItem.setActionCommand(NEW);
			newMenuItem.addActionListener(this);
			newMenuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			fileMenu.add(newMenuItem);


			//   set up Import menu 
			JMenu importMenu = new JMenu(ArMT.labels.getString("fileImportMenu"));
			importMenu.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			importMenu.setMnemonic(KeyEvent.VK_M);
			fileMenu.add(importMenu);
			{
				JMenu importDicMenu = new JMenu(ArMT.labels.getString("fileImportDicMenu"));
				importDicMenu.setFont(new Font("Lucida Sans", Font.BOLD, 12));
				importDicMenu.setMnemonic(KeyEvent.VK_D);
				importMenu.add(importDicMenu);
				
				JMenuItem importDictCurrMnuItem = new JMenuItem(ArMT.labels.getString("fileImportDicCurrMenueItem"));
				importDictCurrMnuItem.setMnemonic(KeyEvent.VK_U);
				importDictCurrMnuItem.setAccelerator(KeyStroke.getKeyStroke(
						KeyEvent.VK_U, ActionEvent.ALT_MASK));
				importDictCurrMnuItem.setActionCommand(DIC_CUR);
				importDictCurrMnuItem.addActionListener(this);
				
				importDicMenu.add(importDictCurrMnuItem);
				
				JMenuItem importDictOldMnuItem = new JMenuItem(ArMT.labels.getString("fileImportDicOldMenueItem"));
				importDictOldMnuItem.setMnemonic(KeyEvent.VK_M);
				importDictOldMnuItem.setAccelerator(KeyStroke.getKeyStroke(
						KeyEvent.VK_M, ActionEvent.ALT_MASK));
				importDictOldMnuItem.setActionCommand(DIC_MOD);
				importDictOldMnuItem.addActionListener(this);
				
				importDicMenu.add(importDictOldMnuItem);
				
				JMenuItem importDictNewMnuItem = new JMenuItem(ArMT.labels.getString("fileImportDicNewMenueItem"));
				importDictNewMnuItem.setMnemonic(KeyEvent.VK_W);
				importDictNewMnuItem.setAccelerator(KeyStroke.getKeyStroke(
						KeyEvent.VK_W, ActionEvent.ALT_MASK));
				importDictNewMnuItem.setActionCommand(DIC_NEW);
				importDictNewMnuItem.addActionListener(this);
			
				importDicMenu.add(importDictNewMnuItem);
				

				JMenuItem importTxtMnuItem = new JMenuItem(ArMT.labels.getString("fileImportTextMenuItem"));
				importTxtMnuItem.setMnemonic(KeyEvent.VK_T);
				importTxtMnuItem.setAccelerator(KeyStroke.getKeyStroke(
						KeyEvent.VK_T, ActionEvent.ALT_MASK));
				importTxtMnuItem.setActionCommand(IMPORT_TXT);
				importTxtMnuItem.addActionListener(this);
				importTxtMnuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
				
				importMenu.add(importTxtMnuItem);
			}
			//set up Export menu 
			JMenu exporetMenu = new JMenu(ArMT.labels.getString("fileExporetMenu"));
			exporetMenu.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			exporetMenu.setMnemonic(KeyEvent.VK_X);
			fileMenu.add(exporetMenu);
			// Set up the exp .dict menu item.
			{  JMenuItem exportDictMnuItem = new JMenuItem(ArMT.labels.getString("fileExportDictionaryMenuItem"));
			exportDictMnuItem.setMnemonic(KeyEvent.VK_I);
			exportDictMnuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_I, ActionEvent.ALT_MASK));
			exportDictMnuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			exportDictMnuItem.setActionCommand(EXPORT_DIC);
			exportDictMnuItem.addActionListener(this);
			exporetMenu.add(exportDictMnuItem);

			JMenuItem exportTxtMnuItem = new JMenuItem(ArMT.labels.getString("fileExportTextMenuItem"));
			exportTxtMnuItem.setMnemonic(KeyEvent.VK_E);
			exportTxtMnuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_E, ActionEvent.ALT_MASK));
			exportTxtMnuItem.setActionCommand(EXPORT_TXT);
			exportTxtMnuItem.addActionListener(this);
			exportTxtMnuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			exporetMenu.add(exportTxtMnuItem);     
			}
			JMenuItem printMenuItem = new JMenuItem(ArMT.labels.getString("filePrintMenuItem"));
			printMenuItem.setMnemonic(KeyEvent.VK_P);
			printMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK));
			printMenuItem.setActionCommand(PRINT);
			printMenuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			printMenuItem.addActionListener(this);
			fileMenu.add(printMenuItem);

			//Set up the quit menu item.
			JMenuItem quitMenuItem = new JMenuItem(ArMT.labels.getString("fileMenuExitItem"));
			quitMenuItem.setMnemonic(KeyEvent.VK_Q);
			quitMenuItem.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_Q, ActionEvent.ALT_MASK));
			quitMenuItem.setActionCommand(QUITE);
			quitMenuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
			//quitMenuItem.addActionListener(this);
			fileMenu.add(quitMenuItem);
		}

		//TRanslation
		JMenu runMenu = new JMenu(ArMT.labels.getString("runMenu"));
		runMenu.setMnemonic(KeyEvent.VK_R);
		runMenu.setFont(new Font("Lucida Sans", Font.BOLD, 12));
		menuBar.add(runMenu);

		JMenuItem qTransMenuItem = new JMenuItem(ArMT.labels.getString("runQTranslateMenuItem"));
		qTransMenuItem.setMnemonic(KeyEvent.VK_N);
		qTransMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_N, ActionEvent.ALT_MASK));
		qTransMenuItem.setActionCommand(QTranslation);
		qTransMenuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
		//
		qTransMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e){   
			output.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			artoen = new ArToEn(input.getText());
			output.setText(artoen.quickTranslation());
			}
		});
		runMenu.add(qTransMenuItem);  
		
		JMenuItem aTransMenuItem = new JMenuItem(ArMT.labels.getString("runATranslateMenuItem"));
		aTransMenuItem.setMnemonic(KeyEvent.VK_C);
		aTransMenuItem.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_C, ActionEvent.ALT_MASK));
		aTransMenuItem.setActionCommand(ATranslation);
		aTransMenuItem.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e){   
			output.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			artoen = new ArToEn(input.getText());
			try {
				output.setText(artoen.accurateTranslation());
			} catch (SAXException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ParserConfigurationException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			}
		});
		aTransMenuItem.setFont(new Font("Lucida Sans", Font.BOLD, 12));
		
		runMenu.add(aTransMenuItem);  
		return menuBar;
	}
	protected void addButtons(JToolBar toolBar) {
		JButton newDocButton = new JButton() ;
		newDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"new_doc1.gif"));
		newDocButton.setActionCommand(NEW); 
		newDocButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e){
				input.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
				setInpuText("");          
			}
		});
		toolBar.add(newDocButton);
		
		JButton openDocButton = new JButton() ;
        openDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"open_doc.gif"));
        openDocButton.setActionCommand(IMPORT_TXT); 
        openDocButton.addActionListener(this);
        toolBar.add(openDocButton);

		JButton saveDocButton = new JButton() ;
		saveDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"save.gif"));
		saveDocButton.setActionCommand(EXPORT_TXT); 
		saveDocButton.addActionListener(this); //new ActionListener()
		toolBar.add(saveDocButton);
//		{
//		public void actionPerformed(ActionEvent e){   
//		try {
//		gui = new ArMT();
//		gui.OpenTxtDialog();
//		} catch (UnsupportedLookAndFeelException e1) {
//		// TODO Auto-generated catch block
//		e1.printStackTrace();
//		} catch (IOException e2) {
//		// TODO Auto-generated catch block
//		e2.printStackTrace();
//		}

//		}
//		});
//		

		JButton parseDocButton = new JButton() ;
		parseDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"parse.gif"));
		parseDocButton.setActionCommand(PARSE); 
		parseDocButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e){ 

				String s = input.getText();
				//JOptionPane.showMessageDialog(null , s);
				MyNormalizer norm;
				try {
					norm = new MyNormalizer(s);
					if(norm.supported() == true )
					{
						String []spl = norm.splitter(s) ;

						for(int j = 0 ; j< spl.length ;j++)
						{     
							JFrame f = new JFrame();
							Tokenizer t =new Tokenizer(spl[j]);
							//JOptionPane.showMessageDialog(null,Lexicon.currentTree.find(t.getTokens()[0]).getEnglishWord());
							ArabicParser arp = new ArabicParser(t.getTokens());
							if(arp.arSentence() == true )
							{
								JOptionPane.showMessageDialog(null,"Arabic Sentence : \""+spl[j]+"\" .");
//							f.getContentPane().add(new JLabel("The sentence : \""+spl[j]+"\"is Ok ."));
//							f.pack() ;
							}
							else JOptionPane.showMessageDialog(null,"The sentence : \""+spl[j]+"\"is not Ok .");

						}
					}
					else JOptionPane.showMessageDialog(null,ArMT.labels.getString("unsupportedInfMess"),ArMT.labels.getString("unsupportedWord"),JOptionPane.INFORMATION_MESSAGE);
				}catch (SAXException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (ParserConfigurationException e2) {
					// TODO Auto-generated catch block
					e2.printStackTrace();
				} catch (HeadlessException e3) {
					// TODO Auto-generated catch block
					e3.printStackTrace();
				} catch (UnsupportedLookAndFeelException e4) {
					// TODO Auto-generated catch block
					e4.printStackTrace();
				}      			

			}
		}
		);
		toolBar.add(parseDocButton); 

		JButton transDocButton = new JButton() ;
		transDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"go.png"));
		transDocButton.setActionCommand(PARSE); 
		transDocButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e){   

			}
		});
		toolBar.add(transDocButton); 

//		JButton searchDocButton = new JButton() ;
//searchDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"search.png"));
//		// searchDocButton.setActionCommand(PARSE); 
//		searchDocButton.addActionListener(new ActionListener()
//		{
//		public void actionPerformed(ActionEvent e){   

//		}
//		});
//		toolBar.add(searchDocButton); 

		JButton printDocButton = new JButton() ;
		printDocButton.setIcon(new ImageIcon("resources"+ArMT.FILE_SEPARATOR+"images"+ArMT.FILE_SEPARATOR+"print.gif"));
		printDocButton.setActionCommand(PRINT); 
		printDocButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{        		
				FileWriter out;
				try {
					out = new FileWriter("lpt1");
					out.write(getOutputText());
					out.write(0x0D); // CR
					out.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		toolBar.add(printDocButton);
	}
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		if (NEW.equals(cmd)) { //new button clicked
		input.setText("");
		}
		else if(PRINT.equals(cmd))
		{
		FileWriter out;
		try {
			out = new FileWriter("lpt1");
			out.write(getOutputText());
			out.write(0x0D); // CR
			out.close();
		} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
		}
		}
		else if (DIC_CUR.equals(e.getActionCommand())){
	   	OpenDictDialog();
		dicTable.setDicState(DicTable.CURRENR) ;
		//dicPane = new JScrollPane(dicTable);
		dicPane.repaint();
	   }
		else if (DIC_MOD.equals(e.getActionCommand())){
		   	OpenDictDialog();  	
			dicTable.setDicState(DicTable.MODIFY) ;
			//dicPane = new JScrollPane(dicTable);
			dicPane.repaint();
		   }
		else if (DIC_CUR.equals(e.getActionCommand())){
		   	OpenDictDialog();
		   	
			dicTable.setDicState(DicTable.NEW) ;
			//dicPane = new JScrollPane(dicTable);
			dicPane.repaint();
		   }
	   else if (IMPORT_TXT.equals(e.getActionCommand())){
	   	try {
	   		 input.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
				OpenTxtDialog();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	   }
	   else if (EXPORT_DIC.equals(e.getActionCommand())){
	  	   try {
			saveDictDialog();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	  }
	   else if (EXPORT_TXT.equals(e.getActionCommand())){
	  	   try {
			SaveTxtDialog();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		}
	   else if(QUITE.equals(cmd))
	   {
		this.removeAll() ;   
	   }
		}

	private void SaveTxtDialog() throws IOException {
		JFileChooser saveTxt=new JFileChooser();
		saveTxt.addChoosableFileFilter(txtExten);
    	saveTxt.setCurrentDirectory(currentDirectory);
    	saveTxt.setDialogTitle(ArMT.labels.getString("saveTxtDialog"));
    	addEncodingAccessory(saveTxt);
    	int returnVal = saveTxt.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION ) {
        	targetFile = saveTxt.getSelectedFile();   
        	if (targetFile==null||targetFile.getName().equals (" "))
    		{
    			JOptionPane.showMessageDialog( null,ArMT.labels.getString("InvalidFileName"),ArMT.labels.getString("InvalidFileName"),JOptionPane.ERROR_MESSAGE );
    		}
        	if ((String)encodingOptions.getSelectedItem() != null) {
                encoding =(String)encodingOptions.getSelectedItem();
            }
        	FileOutputStream file = new FileOutputStream(targetFile);
    		OutputStreamWriter o = new OutputStreamWriter(file,encoding);
    		BufferedWriter bw = new BufferedWriter(o);      
			output.write(bw);
			bw.flush();
			bw.close();
            }
        else if(returnVal == JFileChooser.CANCEL_OPTION)
        {
        	return ;
        }
        currentDirectory = sourceFile;

	}
	private void saveDictDialog() throws FileNotFoundException, UnsupportedEncodingException {
		JFileChooser saveDic=new JFileChooser();
		saveDic.addChoosableFileFilter(xmlExten);
		saveDic.setDialogTitle(ArMT.labels.getString("saveDicDialog"));
		saveDic.setCurrentDirectory(currentDirectory);
		addEncodingAccessory(saveDic);
		int returnVal = saveDic.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION ) {
        	targetFile = saveDic.getSelectedFile();   
        	if (targetFile==null||targetFile.getName().equals (" "))
    		{
    			JOptionPane.showMessageDialog( null,ArMT.labels.getString("InvalidFileName"),ArMT.labels.getString("InvalidFileName"),JOptionPane.ERROR_MESSAGE );
    		}
        	if ((String)encodingOptions.getSelectedItem() != null) {
                encoding =(String)encodingOptions.getSelectedItem();
            }
        try {
			lex.store_data(targetFile.getAbsolutePath(),encoding );
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        }
	}
	private void OpenDictDialog() {		
		JFileChooser dicChooser=new JFileChooser();
		dicChooser.addChoosableFileFilter(xmlExten);
		dicChooser.setCurrentDirectory(currentDirectory);
		dicChooser.setDialogTitle(ArMT.labels.getString("openDicDialog"));
		dicChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		addEncodingAccessory(dicChooser);
		int returnVal = dicChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
        	sourceFile = dicChooser.getSelectedFile();
            try {
				DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
				Document doc = docBuilder.parse(new File(sourceFile.getAbsolutePath()));
		         doc.getDocumentElement().normalize ();//TODO switch for data type ,defined nouns ,indeter nouns ,verbs
		        try{
		         lex.load_4_Data(doc.getElementsByTagName("entry"),WordType.UN_KNOWN);
		        }catch(NullPointerException ne)
		        {
		        	lex.load_3_Data(doc.getElementsByTagName("entry"));
		        }
			} 
            catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}        
				currentDirectory = sourceFile;
            }    
        
	}
	public void OpenTxtDialog() throws IOException {
		JFileChooser txtChooser=new JFileChooser();
		txtChooser.addChoosableFileFilter(txtExten);
		txtChooser.setCurrentDirectory(currentDirectory);
		txtChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		txtChooser.setDialogTitle(ArMT.labels.getString("openTxtDialog"));
		addEncodingAccessory(txtChooser);
		int returnVal = txtChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION ) {
        	sourceFile = txtChooser.getSelectedFile();   
        	if (sourceFile==null||sourceFile.getName().equals (" "))
    		{
    			JOptionPane.showMessageDialog( null,ArMT.labels.getString("InvalidFileName"),ArMT.labels.getString("InvalidFileName"),JOptionPane.ERROR_MESSAGE );
    		}
        	if ((String)encodingOptions.getSelectedItem() != null) {
                encoding =(String)encodingOptions.getSelectedItem();
            }
        	FileInputStream file = new FileInputStream(sourceFile);
    		InputStreamReader i = new InputStreamReader(file,encoding);
    		BufferedReader br = new BufferedReader(i);
            //BufferedReader br = new BufferedReader(new FileReader(sourceFile));
    		currentDirectory = sourceFile;
//    		String buf ,s = null ;
//			while( (buf = br.readLine()) != null )
//			{
//				s += buf;
//				s +="\n";
//				transFrame.setInpuText(s);
//			}
			input.read(br, null);
			br.close();
            }
        else if(returnVal == JFileChooser.CANCEL_OPTION)
        {
        	return ;
        }
        currentDirectory = sourceFile;
}
	private void addEncodingAccessory(JFileChooser fc) {

        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.ipadx = 2;
        c.ipady = 2;

        encPanel = new JPanel(gridbag);

        encPanel.setBorder(new CompoundBorder(
                new CompoundBorder(
                    new EmptyBorder(5, 5, 5, 5),
                    new TitledBorder(ArMT.labels.getString("saveDialogOptions"))),
                new EmptyBorder(5, 5, 5, 5)));
        JLabel saveEncLabel = new JLabel(ArMT.labels.getString("saveDialogSaveEnc"));
        
        encodingOptions = new JComboBox(encOptions);
        encodingOptions.setSelectedItem(encoding);

        c.gridwidth = 1;
        gridbag.setConstraints(saveEncLabel, c);
        encPanel.add(saveEncLabel);
        c.gridwidth = GridBagConstraints.REMAINDER;
        gridbag.setConstraints(encodingOptions, c);
        encPanel.add(encodingOptions);
        fc.setAccessory(encPanel);

    }

	
	
	/**
	 * @return  the xLocation
	 * @uml.property  name="xLocation"
	 */
	public static int getXLocation()
	{
		return xLocation ;
	}
	/**
	 * @return  the yLocation
	 * @uml.property  name="yLocation"
	 */
	public static int getYLocation()
	{
		return yLocation ;

	}
	public void setInpuText(String text)
	{
		input.setText(text);
	}
	public String getOutputText()
	{
		return output.getText();
	}
//	public Cursor getCursorPosition()
//	{
//	return input.getCursor();
//	}
//	public JTextArea getInput()
//	{
//	return input ;
//	}

	public static void setInputTxt(String s)
	{
		input.setText(s);
	}
	public static JTextArea getInputTextArea()
	{
		return input ;
	}
	public JTextArea getOutputTextArea()
	{
		return output ;
	}
//	public void actionPerformed(ActionEvent act) {
//		if(QTranslation.equals(act.getSource()))
//		{
//			artoen = new ArToEn(input.getText());
//		output.setText(artoen.quickTranslation());
//		JOptionPane.showMessageDialog(null, artoen.quickTranslation()) ;
//		}
//		else if(NEW.equals(act.getSource()))
//		{
//			setInpuText("");
//		}
//	}

}
